package com.siss.tenancy.user.utils;

import com.siss.tenancy.exception.BusinessException;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.UUID;

/**
 * 文件名：ImageUtil.java 图片工具类，用于图片转码Base64等 版权：srba 修改人：王行江 修改内容：新增
 * 修改时间：2016-08-19
 **/
@SuppressWarnings("restriction")
public class ImageUtil {
	
//	public static void main(String[] args) throws IOException {
//		String base64 = encodeImgageToBase64(new URL("http://fslab.ufwl.net/group1/M00/00/1D/CgIBW1xKqYCAWSkfAAAQinzVFYw971.jpg"));
//
//		System.out.println(base64);
//	}




    /**
     * @Description 图片转base64
     *  * @param null
     * @return
     * @author dql
     * @Date 2021/3/5 17:03
     **/
    public static String encodeImgageToBase64(BufferedImage bufferedImage) throws IOException {
        ByteArrayOutputStream outputStream = null;
        outputStream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "jpg", outputStream);
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(outputStream.toByteArray());// 返回Base64编码过的字节数组字符串
    }

	/**
	 * 提取base64字符串
	 * 
	 * @param imgStr
	 * @return base64字符串
	 */
	public static String GetImageStrByBase64(String imgStr) {
		return imgStr = imgStr.substring(imgStr.indexOf(",") + 1);
	}

	/**
	 * 将网络图片进行Base64位编码
	 * 
	 * @param imgUrl
	 *            图片的url路径，如http://.....xx.jpg
	 * @return Base64位编码
	 * @throws IOException
	 */
	public static String encodeImgageToBase64(URL imageUrl) throws IOException {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
		ByteArrayOutputStream outputStream = null;
		BufferedImage bufferedImage = ImageIO.read(imageUrl);
		outputStream = new ByteArrayOutputStream();
		ImageIO.write(bufferedImage, "jpg", outputStream);
		// 对字节数组Base64编码
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(outputStream.toByteArray());// 返回Base64编码过的字节数组字符串
	}

	/**
	 * 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
	 * 
	 * @param imgFilePath
	 *            图片路径
	 * @return 图片Base64编码
	 * @throws IOException
	 */
	public static String GetImageStr(String imgFilePath) throws IOException {
		byte[] data = null;
		// 读取图片字节数组
		InputStream in = new FileInputStream(imgFilePath);
		data = new byte[in.available()];
		in.read(data);
		in.close();
		// 对字节数组Base64编码
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(data);
	}

	/**
	 * 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
	 * 
	 * @param data
	 *            图片字节数组
	 * @return 图片Base64编码
	 */
	public static String GetImageStr(byte[] data) {
		// 对字节数组Base64编码
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(data);
	}

	/**
	 * 根据图片base64字符串，保存到指定路径
	 * 
	 * @param imgStr
	 *            图片base64字符串
	 * @param imgFilePath
	 *            保存到指定路径
	 * @return true/false
	 */
	public static boolean GenerateImage(String imgStr, String imgFilePath) {
		// 图像数据为空
		if (imgStr == null)
			return false;
		imgStr = GetImageStrByBase64(imgStr);
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			// Base64解码
			byte[] bytes = decoder.decodeBuffer(imgStr);
			for (int i = 0; i < bytes.length; ++i) {
				// 调整异常数据
				if (bytes[i] < 0) {
					bytes[i] += 256;
				}
			}
			// 生成jpeg图片
			OutputStream out = new FileOutputStream(imgFilePath);
			out.write(bytes);
			out.flush();
			out.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 根据图片base64字符串，保存到指定路径
	 * 
	 * @param imgStr
	 *            图片base64字符串
	 * @return 图片字节
	 */
	public static byte[] GenerateImageToByte(String imgStr) {
		byte[] bytes = null;
		// 图像数据为空
		if (imgStr != null) {
			imgStr = GetImageStrByBase64(imgStr);
			BASE64Decoder decoder = new BASE64Decoder();
			try {
				// Base64解码
				bytes = decoder.decodeBuffer(imgStr);
				for (int i = 0; i < bytes.length; ++i) {
					// 调整异常数据
					if (bytes[i] < 0) {
						bytes[i] += 256;
					}
				}
			} catch (Exception e) {
				throw new BusinessException( "图片转字节失败！");
			}
		}
		return bytes;
	}

	/**
	 * base64转输入流
	 * 
	 * @param imgStr
	 * @return 输入流
	 */
	public static InputStream GenerateImageToStream(String imgStr) {
		ByteArrayInputStream stream = null;
		try {
			imgStr = GetImageStrByBase64(imgStr);
			byte[] bytes1 = GenerateImageToByte(imgStr);
			stream = new ByteArrayInputStream(bytes1);
		} catch (Exception e) {
			throw new BusinessException("图片转字节失败！");
		}
		return stream;
	}

	/**
	 * base64转BufferedImage
	 * 
	 * @param imgStr
	 * @return BufferedImage
	 */
	public static BufferedImage GenerateImageToBufferedImage(String imgStr) {
		BufferedImage image = null;
		try {
			imgStr = GetImageStrByBase64(imgStr);
			InputStream stream = GenerateImageToStream(imgStr);
			image = ImageIO.read(stream);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return image;
	}

	/**
	 * 方法名: generateBufferImageToBase64 描述: BufferedImage转base64 返回类型： String
	 * 
	 * @param bimg
	 * @return
	 * @throws IOException
	 *             作者：wangxj 创建时间：2018年5月15日 下午4:10:09
	 */
	public static String generateBufferImageToBase64(BufferedImage bimg) throws IOException {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		ImageIO.write(bimg, "jpg", outputStream);
		BASE64Encoder encoder = new BASE64Encoder();
		String base64Img = encoder.encode(outputStream.toByteArray());
		return base64Img;
	}

	/**
	 * 字符串转图片
	 * 
	 * @param base64String
	 */
	public static String base64StringToImage(String base64String, String toImagePath, String imageType,
			HttpServletRequest request) {
		// 图像数据为空
		if (base64String == null)
			return null;
		base64String = GetImageStrByBase64(base64String);
		BASE64Decoder decoder = new BASE64Decoder();

		String filePath = request.getRealPath(toImagePath);
		File fileFolder = new File(filePath);
		if (!fileFolder.exists()) { // 如果文件夹不存在,则创建一个
			fileFolder.mkdirs();
		}

		try {
			// Base64解码
			byte[] bytes = decoder.decodeBuffer(base64String);
			for (int i = 0; i < bytes.length; ++i) {
				// 调整异常数据
				if (bytes[i] < 0) {
					bytes[i] += 256;
				}
			}
			UUID uuid = UUID.randomUUID();
			String uploadFileName = uuid.toString().replaceAll("-", "") + "." + imageType;

			OutputStream out = new FileOutputStream(filePath + "/" + uploadFileName);
			out.write(bytes);
			out.flush();
			out.close();

			return toImagePath + uploadFileName;
		} catch (Exception e) {
			return null;
		}

	}
}
